package com.ophiux.cs.application.user.impl.user;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ophiux.cs.application.core.AppResultCode;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.application.core.Throws.ParamException;
import com.ophiux.cs.application.user.dto.LoginRequest;
import com.ophiux.cs.application.user.dto.LoginResponse;
import com.ophiux.cs.application.user.dto.addUserRecoreRequest;
import com.ophiux.cs.application.user.dto.getUserRecoreRequest;
import com.ophiux.cs.application.user.dto.getUserRecoreResponse;
import com.ophiux.cs.application.user.dto.updateUserRecoreInfoRequest;
import com.ophiux.cs.application.user.impl.recore.AddUserRecoreService;
import com.ophiux.cs.application.user.impl.recore.getUserRecoreService;
import com.ophiux.cs.application.user.impl.recore.updateUserRecoreService;
import com.ophiux.cs.domain.user.domainservice.UserDomainService;
import com.ophiux.cs.domain.user.model.entity.User;
import com.ophiux.cs.domain.user.model.entity.UserLoginRecore;
import com.ophiux.cs.domain.user.repositories.IUserRepository;
import com.ophiux.utils.common.DateUtil;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class UserLoginService {
	
	@Autowired
	IUserRepository iUserRepository;
	@Autowired
	UserDomainService userDomainService;
	@Autowired
	AddUserRecoreService addUserRecoreService;
	@Autowired
	getUserRecoreService getUserRecoreService;
	@Autowired
	updateUserRecoreService updateUserRecoreService;

	
	@SuppressWarnings("static-access")
	public Result<LoginResponse> Login(LoginRequest dto) {
		LoginResponse resp = new LoginResponse();
		try {
			/**
			 * 1、验证sign签名是否合法(验证方式待定)
			 * 2、验证参数是否允许为空
			 * 3、执行业务 获取返回参数 与 返回签名串
			 */
			try {	
				//验证参数是否允许为空
				dto.paramVer();
			} catch (ParamException e) {
				return Result.fail(ResultEnum.requestParamFail.getCode(), e.getMessage()); 
			}
			
			List<User> userList = iUserRepository.getUserByUserAcc(dto.getUSER_ACC());
			if(userList !=null && userList.size() != 0) {
				String userName = dto.getUSER_ACC();
				String pwd = dto.getUSER_PWD();
				String roleId = dto.getROLE();
				
				boolean loginPd = false;
				String userId = "";
				for (int i = 0; i < userList.size(); i++) {
					boolean userLoginVer = userList.get(i).validateLogin(userName, pwd, roleId);
					if(userLoginVer) {
						loginPd = true;//登录验证通过
						userId = userList.get(i).getUSER_ID();
						break;
					}
				}
				
				if(loginPd) {//登录验证通过
					getUserRecoreRequest getRecoreReq = new getUserRecoreRequest();
					getRecoreReq.setUSER_ID(userId);
					Result<getUserRecoreResponse> recoreRes = getUserRecoreService.getUserRecore(getRecoreReq);
					
					if(recoreRes.getRESULT().equals(Result.RESULT_SUCCESS) && recoreRes.getERROR_CODE().equals(AppResultCode.SUCCESS)) {
						if(recoreRes.getRESPONSE() != null) {//当前登录用户存在登录记录 更新之前的登录记录为无效
							updateUserRecoreInfoRequest updateUserRecoreDto = new updateUserRecoreInfoRequest();
							updateUserRecoreDto.setUSER_ID(userId);
							updateUserRecoreDto.setLOGOUT_TIME(DateUtil.getCurDateStr());
							updateUserRecoreDto.setSTATE(UserLoginRecore.status_fail);
							updateUserRecoreService.updateUserRecoreInfo(updateUserRecoreDto);
						}
						String token = userDomainService.getToken();
						//组建参数 调用 用户登录信息 记录服务
						addUserRecoreRequest addRecordDto = new addUserRecoreRequest();
						addRecordDto.setUSER_ID(userId);
						addRecordDto.setLOGIN_TOKEN(token);
						addRecordDto.setPLATFORM_ID("");//登录平台暂定为空  后期商榷
						addUserRecoreService.addUserRecore(addRecordDto);
						
						resp.setACCESS_TOKEN(token);
						resp.setUSER_ID(userId);
					}else {//查询用户登录信息失败 或者 异常
						return Result.fail(ResultEnum.LoginFail.getCode(),ResultEnum.LoginFail.getMsg() );
					}
					
				}else {//登录验证不通过
					return Result.fail(ResultEnum.LoginFail.getCode(),ResultEnum.LoginFail.getMsg() );
				}
			}else {
				//账号不存在
//				resp.setACCESS_TOKEN("");
				return Result.fail(ResultEnum.NotFundUser.getCode(),ResultEnum.NotFundUser.getMsg() );
			}
		} catch (Exception e) {
			log.info("Login接口异常：",e);
			e.printStackTrace();
			return Result.fail(ResultEnum.requestException);
		}
		return Result.success(resp, "登录成功");
	}
}
